<script setup lang="ts">
import * as THREE from 'three'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
import { ref, onMounted } from 'vue'

const domEl = ref(null)
const domEl2 = ref(null)

const initCanvas = (domEl, noResponse = false) => {
  const canvas = domEl
  const renderer = new THREE.WebGLRenderer({antialias: true, canvas})

  const camera = new THREE.PerspectiveCamera(40, 2, 0.1, 1000)
  camera.position.z = 40

  const scene = new THREE.Scene()
  scene.background = new THREE.Color(0xAAAAAA)

  const radius = 7
  const widthSegments = 12
  const heightSegments = 8
  const geometry = new THREE.SphereGeometry(radius, widthSegments, heightSegments)
  const material = new THREE.PointsMaterial({
    color: 'red',
    size: 3,     // in world units
  })
  const points = new THREE.Points(geometry, material)
  scene.add(points)

  const controls = new OrbitControls( camera, renderer.domElement )

  function resizeRendererToDisplaySize(renderer) {
    const canvas = renderer.domElement
    const pixelRatio = window.devicePixelRatio
    const width = canvas.clientWidth * pixelRatio | 0
    const height = canvas.clientHeight * pixelRatio | 0
    const needResize = canvas.width !== width || canvas.height !== height
    if (needResize) {
      renderer.setSize(width, height, false)
    }
    return needResize
  }

  function render() {
    if (!noResponse && resizeRendererToDisplaySize(renderer)) {
      const canvas = renderer.domElement
      camera.aspect = canvas.clientWidth / canvas.clientHeight
      camera.updateProjectionMatrix()
    }

    points.rotation.x += 0.01
    points.rotation.y += 0.01

    controls.update()
    renderer.render(scene, camera)

    requestAnimationFrame(render)
  }

  requestAnimationFrame(render)
}

onMounted(() => {
  initCanvas(domEl.value)
  initCanvas(domEl2.value, true)
})

</script>

<template>
  <div class="w-screen h-screen flex">
    <canvas ref="domEl" class="w-1/2 h-full"></canvas>
    <canvas ref="domEl2" class="w-1/2 h-full"></canvas>
  </div>
</template>

<style scoped lang="scss">

</style>